﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;

namespace Tax.Service
{
    using Tax.Util;
    using Tax.DataAccess.Models;
    using Tax.Contract.IServices;
    using Tax.Domain.Model;
    using Tax.Domain.Query;

    public class BusinessService : IBusinessService
    {
        private TaxationContext _context;
        public BusinessService(TaxationContext context)
        {
            _context = context;
        }

        public Task<CityInfoListModel> GetCityInfo()
        {
            return Task.Run(() =>
            {
                CityInfoListModel model = new CityInfoListModel();
                model.LoginID = SessionInfo.LoginId;
                var user = _context.User.Where(u => u.LoginId == model.LoginID).FirstOrDefault();
                if (user != null)
                {
                    model.DefaultQueryCityCode = user.DefaultQueryCityCode;
                }
                model.InfoList = _context.City.Where(c => c.Deleted == false)
                            .Select(c => new CityInfoModel()
                            {
                                CityName = c.CityName,
                                CityCode = c.CityCode
                            }).ToList();

                return model;
            });
        }

        public Task<CalculateModel> CalculateTaxSalary(CalculateQuery query)
        {
            return Task.Run(() =>
            {
                CalculateModel model = new CalculateModel();

                var city = _context.City.Where(c => c.CityCode == query.CityCode).FirstOrDefault();
                if (city != null)
                {
                    var user = _context.User.Where(u => u.LoginId == query.LoginID).FirstOrDefault();
                    if (user != null)
                    {
                        user.DefaultQueryCityCode = query.CityCode;
                        _context.SaveChanges(true);
                    }
                    decimal salary = query.Salary * (100 - city.AnnuityRate - city.MedicareRate - city.UnemployRate - city.FundRate) / 100;

                    var taxRate = _context.TaxRate.Where(t => t.Deleted == false && t.MoneyLevel >= salary).OrderBy(o => o.MoneyLevel).FirstOrDefault();
                    if (taxRate == null)
                    {
                        taxRate = _context.TaxRate.Where(t => t.Deleted == false).OrderByDescending(o => o.MoneyLevel).First();
                    }
                    salary = salary - ( salary * taxRate.Rate / 100 - taxRate.Offset );
                    model.Salary = salary.ToString("n");
                }
                else
                {
                    model = null;
                }

                return model;
            });
        }
    }
}
